package com.laundry.user.repository

import android.content.Context
import com.laundry.user.network.ApiService
import com.laundry.user.network.LoginRequest
import com.laundry.user.network.LoginResponse
import com.laundry.user.network.NetworkResult
import com.laundry.user.model.User
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.junit.MockitoJUnitRunner
import retrofit2.Response
import org.junit.Assert.*

@RunWith(MockitoJUnitRunner::class)
class LaundryRepositoryTest {
    
    @Mock
    private lateinit var context: Context
    
    @Mock
    private lateinit var apiService: ApiService
    
    private lateinit var repository: LaundryRepository
    
    @Before
    fun setup() {
        repository = LaundryRepository(context)
        // 注入mock的apiService（实际项目中需要使用依赖注入框架）
    }
    
    @Test
    fun `login success should return success result`() = runTest {
        // Given
        val phone = "13800138000"
        val password = "password123"
        val mockUser = User(
            id = "1",
            name = "测试用户",
            phone = phone,
            email = "test@example.com",
            avatar = ""
        )
        val mockResponse = LoginResponse(
            token = "mock_token",
            user = mockUser,
            expiresIn = 3600
        )
        
        `when`(apiService.login(LoginRequest(phone, password)))
            .thenReturn(Response.success(mockResponse))
        
        // When
        val result = repository.login(phone, password).first()
        
        // Then
        assertTrue(result is NetworkResult.Success)
        assertEquals(mockResponse, (result as NetworkResult.Success).data)
    }
    
    @Test
    fun `login failure should return error result`() = runTest {
        // Given
        val phone = "13800138000"
        val password = "wrong_password"
        
        `when`(apiService.login(LoginRequest(phone, password)))
            .thenReturn(Response.error(401, mock()))
        
        // When
        val result = repository.login(phone, password).first()
        
        // Then
        assertTrue(result is NetworkResult.Error)
        assertTrue((result as NetworkResult.Error).message.contains("登录失败"))
    }
    
    @Test
    fun `network exception should return error result`() = runTest {
        // Given
        val phone = "13800138000"
        val password = "password123"
        
        `when`(apiService.login(LoginRequest(phone, password)))
            .thenThrow(RuntimeException("Network error"))
        
        // When
        val result = repository.login(phone, password).first()
        
        // Then
        assertTrue(result is NetworkResult.Error)
        assertTrue((result as NetworkResult.Error).message.contains("网络错误"))
    }
}
